using System.Linq;
using System.Threading.Tasks;
using DailyPoetryX.AzureStorage.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace DailyPoetryX.AzureStorage {
    /// <summary>
    /// 获得收藏Blob。
    /// </summary>
    public class GetFavoriteBlob {
        /// <summary>
        /// 身份验证服务。
        /// </summary>
        private static IAuthenticationService _authenticationService;

        /// <summary>
        /// 授权服务。
        /// </summary>
        private static IAuthorizationService _authorizationService;

        /// <summary>
        /// 收藏存储。
        /// </summary>
        private static IFavoriteStorage _favoriteStorage;

        /// <summary>
        /// 获得收藏Blob。
        /// </summary>
        /// <param name="authenticationService">身份验证服务。</param>
        /// <param name="authorizationService">授权服务。</param>
        /// <param name="favoriteStorage">收藏服务。</param>
        public GetFavoriteBlob(IAuthenticationService authenticationService,
            IAuthorizationService authorizationService,
            IFavoriteStorage favoriteStorage) {
            _authenticationService = authenticationService;
            _authorizationService = authorizationService;
            _favoriteStorage = favoriteStorage;
        }

        [FunctionName("GetFavoriteBlob")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
            HttpRequest req, ILogger log) {
            log.LogInformation(
                "GetFavoriteBlob HTTP trigger function processed a request.");

            var authenticationHelperResult =
                await AuthorizationHelper.Authorize(req, log,
                    _authenticationService, _authorizationService);
            if (!authenticationHelperResult.Passed) {
                return authenticationHelperResult.ActionResult;
            }

            var name = authenticationHelperResult.AuthenticationResult.Name;

            var bytes = await _favoriteStorage.GetAsync(name);
            if (bytes == null) {
                return new NoContentResult();
            }

            return new FileContentResult(bytes, "application/zip");
        }
    }
}